<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class ShopOrderGoodsCommand extends Command
{
    /**
     * 创建订单商品信息
     *
     * @var string
     */
    protected $signature = 'command:shopOrderGoods';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $list = DB::table('shop_order')->get();
        foreach ($list as $v) {
            $product = DB::table('shop_product')->where('product_id', $v->product_id)->first();
            $spec = DB::table('shop_product_specs')->where('ps_id', $v->ps_id)->first();
            $item = DB::table('shop_order_goods')->where('order_id', $v->order_id)->first();
            if (!is_null($item)) {
                DB::table('shop_order_goods')->where('order_id', $v->order_id)->update([
                    'price' => bcsub($item->original_price, $item->discount, 2),
                ]);
            }
            if (!is_null($spec)) $originalPrice = $spec->ps_price_underlined;
            else $originalPrice = $v->order_product_price;

            if ($v->order_product_price * 1 > $originalPrice) $originalPrice = $v->order_product_price;

            $discountSpecial = bcsub($originalPrice, $v->order_product_price, 2);
            $discount = bcadd($discountSpecial, $v->sub_price, 2);

            DB::table('shop_order_goods')->insert([
                'order_id' => $v->order_id,
                'seller_id' => $v->sell_user_id,
                'product_file_id' => $product->product_avatar ?? '',
                'spec_file_id' => $spec->ps_avatar ?? '',
                'product_id' => $v->product_id,
                'spec_id' => $v->ps_id,
                'title' => $product->product_name ?? '',
                'spec' => $spec->ps_name ?? '',
                'quantity' => $v->order_product_num,
                'original_price' => $originalPrice,
                'special_price' => $v->order_product_price,
                'price' => bcsub($originalPrice, $discount, 2),
                'discount' => $discount,
                'discount_special' => $discountSpecial,
                'discount_sub' => $v->sub_price,
                'created_at' => date('Y-m-d H:i:s', $v->created_at),
                'updated_at' => date('Y-m-d H:i:s', $v->created_at),
            ]);
        }
    }
}
